/**
 * 2017.4.28
 */
package cn.edu.bjtu.entity.impl;

import java.util.Date;
import java.util.concurrent.locks.ReadWriteLock;

import org.springframework.context.ApplicationEventPublisher;

import cn.edu.bjtu.entity.ExecuteContext;
import cn.edu.bjtu.entity.ExecuteResult;

/**
 * 这个主要是对于一些状态进行处理,
 * 所需要的所有的成员变量都是由Builder传入
 * @author alex
 *
 */
public abstract class AsynModelBuildStateSupportExecuteContext<R> implements ExecuteContext,ExecuteResult<R>{

	protected ApplicationEventPublisher publisher;
	volatile boolean success =  false;
	volatile boolean executing = false;
	volatile private boolean exist = false;
	
	volatile private boolean expired = false; 
	
	volatile protected String msg = null;
	private Date time = null;
	
	public Date getDate(){
		return time;
	}
	public AsynModelBuildStateSupportExecuteContext(ApplicationEventPublisher publisher, Date date) {
		this.publisher = publisher;
		time = date;
	}

	@Override
	public String getInputDir() {
		return null;
	}

	@Override
	public String getOutPutDir() {
		return null;
	}
	/**
	 * 如果是异步实现,请把状态变量添加上volatile
	 */
	@Override
	public boolean isAsync() {
		return true;
	}
	protected abstract void fireInternal();
	
	/**
	 * 执行完成之后结果都保存到"执行环境"中了.
	 */
	public final void fire(){
		try{
			executing = true;
			fireInternal();
		}catch(Exception e){
			success = false;
			exist = false;
			msg = e.getMessage();
		}finally{
		}
	}
	@Override
	public boolean isSuccess() {
		return success;
	}
	@Override
	public boolean isFailed() {
		return !isSuccess();
	}
	@Override
	public String getTipMessage() {
		return msg;
	}
	@Override
	public boolean isExecuting() {
		return executing;
	}
	public boolean isExist(){
		return this.exist;
	}
	@Override
	public boolean isNoCache() {
		return false;
	}
	
	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}
	/**
	 * @param msg the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}
	/**
	 * @param success the success to set
	 */
	public void setSuccess(boolean success) {
		this.success = success;
	}
	/**
	 * @param executing the executing to set
	 */
	public void setExecuting(boolean executing) {
		this.executing = executing;
	}
	/**
	 * @param exist the exist to set
	 */
	public void setExist(boolean exist) {
		this.exist = exist;
	}
	/**
	 * @return the expired
	 */
	public boolean isExpired() {
		return expired;
	}
	/**
	 * @param expired the expired to set
	 */
	public void setExpired(boolean expired) {
		this.expired = expired;
	}
	
	public abstract void executeAsync();
	public abstract ReadWriteLock getLock();
}
